package com.fight.strive.sys.modules.camunda.service.impl;

import com.fight.strive.sys.modules.camunda.dto.WorkflowDeploymentDto;
import com.fight.strive.sys.modules.camunda.service.WorkflowDeploymentService;
import com.fight.strive.sys.modules.exception.StriveException;
import com.fight.strive.sys.modules.request.dto.PageRequest;
import com.fight.strive.sys.modules.response.dto.PageData;
import com.fight.strive.sys.modules.sysadmin.utils.SysAdminUtils;
import com.fight.strive.sys.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.repository.DeploymentQuery;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZHOUXIANG
 */
@Service
@Slf4j
public class WorkflowDeploymentServiceImpl implements WorkflowDeploymentService {

    @Resource
    private RepositoryService repositoryService;

    @Override
    public void bpmnModelDeployFile(MultipartFile file, String name) {
        Long tenantId = SysAdminUtils.getCurrentTenantId();
        try {
            repositoryService.createDeployment()
                    .tenantId(String.valueOf(tenantId))
                    .name(name)
                    .addInputStream(file.getOriginalFilename(),
                            file.getInputStream())
                    .deploy();
        } catch (Exception e) {
            throw new StriveException("流程部署失败".concat(e.getMessage()));
        }
    }

    @Override
    public void bpmnModelDeployText(String text, String name) {
        Long tenantId = SysAdminUtils.getCurrentTenantId();
        try {
            repositoryService.createDeployment()
                    .tenantId(String.valueOf(tenantId))
                    .name(name)
                    .addString("process.bpmn", text)
                    .deploy();
        } catch (Exception e) {
            throw new StriveException("流程部署失败".concat(e.getMessage()));
        }
    }

    @Override
    public void redeployResource(String id) {
        Long tenantId = SysAdminUtils.getCurrentTenantId();
        repositoryService.createDeployment()
                .tenantId(String.valueOf(tenantId))
                .nameFromDeployment(id).addDeploymentResources(id)
                .deploy();
    }

    @Override
    public PageData<WorkflowDeploymentDto> listDeploymentByPage(
            PageRequest<WorkflowDeploymentDto> pageRequest) {
        WorkflowDeploymentDto condition = pageRequest.getCondition();
        Long tenantId = SysAdminUtils.getCurrentTenantId();
        DeploymentQuery deploymentQuery = repositoryService.createDeploymentQuery()
                .tenantIdIn(String.valueOf(tenantId));
        // 根据部署名称查询
        if (StringUtils.isNotBlank(condition.getName())) {
            deploymentQuery.deploymentNameLike(
                    "%".concat(condition.getName()).concat("%"));
        }
        List<WorkflowDeploymentDto> deploymentList = new ArrayList<>();
        List<Deployment> deployments = deploymentQuery
                .orderByDeploymentTime().desc()
                .listPage((int) pageRequest.getStart(0),
                        (int) pageRequest.getRows());
        deployments.forEach(d -> {
            WorkflowDeploymentDto dto = new WorkflowDeploymentDto();
            dto.setId(d.getId())
                    .setName(d.getName())
                    .setDeploymentTime(d.getDeploymentTime())
                    .setSource(d.getSource())
                    .setTenantId(d.getTenantId());
            deploymentList.add(dto);
        });
        long total = deploymentQuery.count();
        PageData<WorkflowDeploymentDto> pageData = new PageData<>(pageRequest);
        pageData.setTotal(total).calcPages().setContent(deploymentList);
        return pageData;
    }

    @Override
    public void deleteDeploymet(String id) {
        repositoryService.deleteDeployment(id, true);
    }
}
